package com.moneywelcome.loanserviceassembly.apiimpl;

import cn.hutool.core.date.DateUtil;
import com.moneywelcome.antifraudfacade.api.UserIdcardApi;
import com.moneywelcome.antifraudfacade.info.IdcardInfo;
import com.moneywelcome.api.ApplicationScorecardApi;
import com.moneywelcome.api.UserGradeApi;
import com.moneywelcome.atomloanfacade.api.InstalmentRuleApi;
import com.moneywelcome.atomloanfacade.api.LoanProductApi;
import com.moneywelcome.atomloanfacade.api.UserLoanApi;
import com.moneywelcome.atomloanfacade.form.SaveLoanForm;
import com.moneywelcome.atomloanfacade.info.InstalmentRuleInfo;
import com.moneywelcome.atomloanfacade.info.LoanProductInfo;
import com.moneywelcome.http.ServletUtil;
import com.moneywelcome.jwt.JWTHelper;
import com.moneywelcome.loanservicefacade.api.LoanServiceApi;
import com.moneywelcome.loanservicefacade.forms.AuthenticateForm;
import com.moneywelcome.loanservicefacade.forms.LoanForm;
import com.moneywelcome.loanservicefacade.info.LoanInfo;
import com.moneywelcome.loanservicefacade.info.OverdueRecordsInfo;
import com.moneywelcome.params.PageParam;
import com.moneywelcome.results.PageResult;
import com.moneywelcome.results.Result;
import com.moneywelcome.validate.ValidationUtils;
import com.moneywelcome.vo.ComputeVo;
//import io.seata.spring.annotation.GlobalTransactional;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.FileNotFoundException;
import java.util.List;


@Api(tags = "用户借贷服务")
@RestController
@Slf4j
public class LoanServiceApiImpl implements LoanServiceApi {

    @Autowired
    private UserIdcardApi idcardApi;

    @Autowired
    private LoanProductApi loanProductApi;


    @Autowired
    private ApplicationScorecardApi applicationScorecardApi;

    @Autowired
    private UserGradeApi userGradeApi;

    @Autowired
    private InstalmentRuleApi instalmentRuleApi;

    @Autowired
    private UserLoanApi userLoanApi;

    /**
     * 用户贷款
     * @return
     */
//    @GlobalTransactional
    @Override
    public Result loan(@RequestBody LoanForm form) {
        ValidationUtils.validate(form);
        log.info("用户贷款:{}",form);
        // 获取userId
        Integer userId = Integer.valueOf(ServletUtil.getHttpServletRequest().getHeader("userId"));
        //查询贷款产品
        LoanProductInfo productInfo = loanProductApi.getLoanProductById(form.getLoanProductId()).getData();
        //查询用户评分
        Integer userGrade = userGradeApi.getGradeByUser(userId).getData().getUserGrade();
        if (userGrade<productInfo.getBaseGrade()&&form.getMoney()>productInfo.getBaseMoney())
            return Result.fail("超过贷款额度");
        if ((userGrade<productInfo.getLowGrade()))
            return Result.fail("没有贷款资格");
        if (userGrade>=productInfo.getLowGrade()&&userGrade<productInfo.getBaseGrade())
            if (form.getMoney()>productInfo.getLowestMoney()) return Result.fail("超过贷款额度");
        if (userGrade>=productInfo.getBaseGrade())
            if (form.getMoney()>productInfo.getBaseMoney()+productInfo.getIncreasePerStage()*((userGrade-productInfo.getBaseGrade())/10))
                return Result.fail("超过贷款额度");
        //查询贷款利率
        List<InstalmentRuleInfo> ruleInfos = instalmentRuleApi.getRulesByProduct(productInfo.getLoanProductId()).getData();
        InstalmentRuleInfo rule=null;
        for (InstalmentRuleInfo r : ruleInfos) {
            if (r.getInstalmentPeroid()==form.getLoanStage()) {
                rule=r;
                break;
            }
        }
        if (null==rule) return Result.fail("分期数不合规");
        //保存贷款数据
        SaveLoanForm saveLoanForm = new SaveLoanForm();
        saveLoanForm.setUserId(userId);
        saveLoanForm.setLoanRate(rule.getInstalmentRate());
        saveLoanForm.setLoanMoney(form.getMoney());
        saveLoanForm.setLoanStage(rule.getInstalmentPeroid());
        saveLoanForm.setServiceCharge(0.001);
        saveLoanForm.setLoanProductId(rule.getLoanProductId());
        saveLoanForm.setBankAccount(form.getBankAccount());

        Result saveLoan = userLoanApi.saveLoan(saveLoanForm);
        return saveLoan.isSuccess()?Result.success(saveLoanForm):Result.fail();
    }

    /**
     * 首次使用资质申请,进行评分
     * @return
     */
//    @GlobalTransactional
    @Override
    public Result authenticate(@RequestBody AuthenticateForm form) throws FileNotFoundException {
        ValidationUtils.validate(form);
        log.info("资质申请:{}",form);
        //保存数据
        // 获取userId
        Integer userId = Integer.valueOf(ServletUtil.getHttpServletRequest().getHeader("userId"));
        log.info("userId:{}",userId);
        //查询信息
        if (userGradeApi.getGradeByUser(userId).isSuccess())
            return Result.fail("已完成评估");
        String birthday = idcardApi.getIdcard(userId).getData().getBirthday();
        String birthYear = birthday.split("-")[0];
        int age = DateUtil.thisYear() - Integer.valueOf(birthYear);
        //计算评分
        ComputeVo computeVo = new ComputeVo();
        computeVo.setAvailabilityRate(Math.random());
        computeVo.setAge(age);
        computeVo.setOverdueOneMonth((int) (Math.random()*10));
        computeVo.setOverdueTwoMonth((int) (Math.random()*6));
        computeVo.setOverdueThreeMonth((int) (Math.random()*3));
        float score = Float.valueOf(applicationScorecardApi.computeScore(computeVo).getData().toString().trim());
        //保存评分
        return userGradeApi.saveGrade(userId, (int) score);
    }


    /**
     * 查询所有贷款产品
     * @return
     */
    @Override
    public Result loanProduct(PageParam pageParam) {
        return Result.success(userLoanApi.getLoans(pageParam));
    }


    /**
     * 根据用户id获取贷款
     * @param userId
     * @return
     */
    @Override
    public Result<PageResult<LoanInfo>> getLoanByUser(Integer userId,PageParam pageParam) {
        return Result.success(userLoanApi.getLoanByUser(userId,pageParam));
    }

    /**
     * 根据登录用户查询贷款
     * @return
     */
    @Override
    public Result<PageResult<LoanInfo>> getLoanByUser(PageParam pageParam) {
        Integer userId = Integer.valueOf(ServletUtil.getHttpServletRequest().getHeader("userId"));
        return Result.success(userLoanApi.getLoanByUser(userId,pageParam));
    }


    /**
     * 获取所有用户所有未处理逾期记录
     * @return
     */
    @Override
    public Result<PageResult<OverdueRecordsInfo>> getOverdueRecords() {
        return Result.success();
    }

    /**
     * 登录用户查询逾期记录
     * @return
     */
    @Override
    public Result<PageResult<OverdueRecordsInfo>> userOverdueRecord() {
        return Result.success();
    }


}
